/**
 * @author vivi
 * @description
 * @date 2024/5/24
 */
public class demo3 {
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    int n = 0, m = 0;
    int[][] dist = new int[1024][1024];
    public int solve (int[][] matrix) {
        // write code here
        n = matrix[0].length;
        m = matrix.length;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dist[i][j] = -1;
            }
        }

        int ret = 1;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                ret = Math.max(ret, dfs(matrix, i, j));
            }
        }
        return ret;
    }

    public int dfs(int[][] matrix, int i, int j) {
        if (dist[i][j] != -1) {
            return dist[i][j];
        }

        int len = 1;
        for (int k = 0; k < 4; k++) {
            int x = dx[k] + i;
            int y = dy[k] + j;
            if (x >= 0 && x < n && y >= 0 && y < m && matrix[x][y] > matrix[i][j]) {
                len = Math.max(len, 1 + dfs(matrix, x, y));
            }
        }
        dist[i][j] = len;
        return len;
    }
}
